Ext.require([
    'Ext.tree.*',
    'Ext.data.*',
    'Ext.layout.container.HBox',
    'Ext.window.MessageBox'
]);
var queryList = {};
var conditionList = {};
var conditions = {};
var conditionsTemp = {};
var q_id = null;
var unit = 0;
var is_page = 0;
var q_title = null;
var columns = new Array();
var configColumns = new Array();
var fields = {};
var fieldsTemp = {};
var codeMap = {};
var task = true;
var timer = true;
var task1 = true;
var timer1 = true;
var ddTemp = "";
var showRecord = {};
var currentNode;
var currentReport;
var conditionlength = 0;
var fieldsLength = 0;
var dragTemp = {};
var oldTemp = "";
var dragFlag = false;
var panelDragTemp = {};
var panelDragFlag = false;
var FlagForPanel = false;
var deleteFlag = false;
var singleHeadFlag = false;
Ext.onReady(function() {
    var panel=  new Ext.panel.Panel ({
    	renderTo:Ext.getBody(),
    	height:'100%',
        width:'100%',
	    layout: 'border',
        defaults: {
            split: true,                  //是否有分割线
            collapsible: true           //是否可以折叠
        },
        dockedItems: [{
	          xtype: 'toolbar',
	          dock: 'top',//bottom
	          items: buttons
			}],
        border: false,
        items: [initLeftTree(),initPanel(),initRightConfig()]
	});
});

var buttons = [{
			    xtype: 'button',
			    text: '保存报表',
			    name: 'save',
			    disabled: true,
			    icon: '/report/image/sysbutton/save.png',
			    handler: function (self) {
			    	saveReport();
			    }
			},{
                xtype: "button", 
                text: '另存为',
                name:'resave',
                icon: '/report/image/sysbutton/resave.png',
                handler: function () {
                	var manageTreePanel = Ext.ComponentQuery.query('treepanel#manageTree')[0];
				   	 var select = manageTreePanel.getSelectionModel().getSelection()[0];
				   	 if(select && select.get("leaf")){
	                     initWindow_report_resave(select);
				   	 }else{
				   		 Ext.MessageBox.alert('提示', '请选择查询报表');
				   	 }
                }
            },{
			    xtype: 'button',
			    text: '新增目录',
			    icon: '/report/image/sysbutton/add.png',
			    handler: function (self) {
			    	 var manageTreePanel = Ext.ComponentQuery.query('treepanel#manageTree')[0];
				   	 var select = manageTreePanel.getSelectionModel().getSelection()[0];
				   	 var parent_id = "";
				   	 var levelno = 1;
				   	 var parent_name = "全部";
				   	 if(select){
				   		if(select.get("leaf")){
				   			Ext.MessageBox.alert('提示', '请选择目录');
	                		return;
	                	 }
				   		
				   		if(select.get("id")!="root"){
				   			levelno = select.get("depth")+1;
					   		parent_id = select.get('id');
					   		parent_name = select.get('text');
				   		}
				   		initWindow_file_add(parent_id,levelno,parent_name);
				   	 }else{
				   		Ext.MessageBox.alert('提示', '请选择目录');
				   	 }
				   	
			    }
			},{
			    xtype: 'button',
			    text: '修改目录',
			    icon: '/report/image/sysbutton/add.png',
			    handler: function (self) {
			    	 var manageTreePanel = Ext.ComponentQuery.query('treepanel#manageTree')[0];
				   	 var select = manageTreePanel.getSelectionModel().getSelection()[0];
				   	 if(select){
				   		if(select.get("leaf")){
				   			Ext.MessageBox.alert('提示', '请选择目录');
	                		return;
	                	 }
				   		
				   		if(select.get("id") == "root"){
				   			Ext.MessageBox.alert('提示', '请选择具体目录');
	                		return;
				   		}
				   		initWindow_file_update(select.get('id'),select.get('text'));
				   	 }else{
				   		Ext.MessageBox.alert('提示', '请选择目录');
				   	 }
				   	
			    }
			},{
			    xtype: 'button',
			    text: '新增',
			    icon: '/report/image/sysbutton/add.png',
			    handler: function (self) {
			    	 var manageTreePanel = Ext.ComponentQuery.query('treepanel#manageTree')[0];
				   	 var select = manageTreePanel.getSelectionModel().getSelection()[0];
				   	 var parent_id = "";
				   	 if(select){
				   		if(!select.get("leaf") && select.get("id") !='root'){
				   			parent_id = select.get('id');
	                	 }
				   	 }
			    	initWindow_report_config({
			    		xiugai:'xiugai',
			    		parent_id:parent_id
					 });
			    	//Ext.ComponentQuery.query('button[name="import"]')[0].setHidden(true);
			    	//Ext.ComponentQuery.query('button[name="save"]')[0].setDisabled(true);
			    }
			},{
			    xtype: 'button',
			    text: '修改',
			    icon: '/report/image/sysbutton/edit.png',
			    handler: function (self) {
			    	 var manageTreePanel = Ext.ComponentQuery.query('treepanel#manageTree')[0];
				   	 var select = manageTreePanel.getSelectionModel().getSelection()[0];
				   	 if(select && select.get("leaf")){
				   		var id = select.get('id');
				   		var q_is_title = select.get('q_is_title');
	                	var text = select.get('text');
	                	var table = select.get('table');
	                	var unit = select.get('unit');
	                	var q_is_right = select.get('q_is_right');
	                	var q_is_page = select.get('q_is_page');
	                	var q_is_sum = select.get('q_is_sum');
	                	var q_is_openrun = select.get('q_is_openrun');
	                	var q_is_button = select.get('q_is_button');
	                	var q_remark = select.get('q_remark');
	                	var right_level = select.get('right_level');
	                	var export_level = select.get('export_level');
	                	var q_note = select.get('q_note');
	                	var export_data_format = select.get('export_data_format');
						 //判断修改时标题是否有动态参数${}，避免不显示动态参数
						 text = (!!q_title && q_title.indexOf("$") != -1) ? q_title : text;
				   		 var data = {
				   				Q_ID: id,
				   				Q_IS_TITLE: q_is_title,
				   				Q_TITLE: text,
                        		Q_TABLE: table,
                        		MONEY_UNIT: unit,
                        		Q_IS_RIGHT: q_is_right,
                        		Q_IS_PAGE: q_is_page,
                        		Q_IS_SUM: q_is_sum,
                        		Q_IS_OPENRUN: q_is_openrun,
                        		Q_REMARK:q_remark,
                        		Q_IS_BUTTON: q_is_button,
                        		RIGHT_LEVEL:right_level,
							 	EXPORT_LEVEL:export_level,
							 	EXPORT_DATA_FORMAT:export_data_format,
                        		Q_NOTE:q_note
                             };
				    	initWindow_report_config({
				    		xiugai:'xiugai',
				    		edit:true,
				    		data:data
				    	});
				   	 }else{
				   		 Ext.MessageBox.alert('提示', '请先选查询报表再进行修改');
				   	 }
			    }
			},{
			    xtype: 'button',
			    text: '删除',
			    name: 'delete',
			    icon: '/report/image/sysbutton/delete.png',
			    handler: function (btn) {
			   	 var manageTreePanel = Ext.ComponentQuery.query('treepanel#manageTree')[0];
			   	 var select = manageTreePanel.getSelectionModel().getSelection()[0];
			   	 if(select){
			   		 var id = select.get("id");
			   		 var text = select.get("text");
			   		 Ext.Msg.confirm('提示', '请确认是否删除'+text, function (btn_confirm) {
			                if (btn_confirm == 'yes') {
			                	 //发送ajax请求，删除数据
                                $.post("/sys-report/deleteQueryReport", {
                                	Q_ID: id
								}, function(data) {
                                    if (data.success) {
                                        Ext.toast({
                                            html: "删除成功！",
                                            closable: false,
                                            align: 't',
                                            slideInDuration: 400,
                                            minWidth: 400
                                        });
                                        manageTreePanel.getStore().load();
//                                        Ext.ComponentQuery.query('button[name="import"]')[0].setHidden(true);
                                        Ext.ComponentQuery.query('button[name="save"]')[0].setDisabled(true);
                                        var fieldTree = Ext.ComponentQuery.query('treepanel#fieldTree')[0];
                                        var fieldStore = fieldTree.getStore();
                                        fieldStore.getProxy().extraParams = {
                                        	table:""
                                        };
                                        fieldStore.load();
                                        var mainPanel = Ext.ComponentQuery.query('panel#mainPanel')[0];
                                		mainPanel.removeAll(true);
                                		var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
                    	        		rightConfig.removeAll(true);
                    	        		conditions = {};
                    	        		fields = {};
                    	        		queryList = {};
                    	        		fieldsTemp = {};
                    	        		conditionsTemp = {};
                    	        		deleteFlag = true;
                                    } else {
                                        Ext.MessageBox.alert('提示', '删除失败！' + data.message);
                                    }
                                }, "json");
			                }
			            }); 
			   	 }else{
			   		 Ext.MessageBox.alert('提示', '请先选查询报表再进行删除');
			   	 }
			    }
			},{
                xtype: 'button',
                text: '预览',
                icon: '/report/image/sysbutton/search.png',
                handler: function (self) {
			    	 var manageTreePanel = Ext.ComponentQuery.query('treepanel#manageTree')[0];
				   	 var select = manageTreePanel.getSelectionModel().getSelection()[0];
				   	 if(select && select.get("leaf")){
	                	 var q_id =  select.get('id');
	                     var Q_NAME = select.get('text');
	                     var yl_url = "/report/page/plat/query/reportQuery.html?code="+q_id+"&adcode="+adcode;
	                 	window.open(yl_url, '_blank');
				   	 }else{
				   		 Ext.MessageBox.alert('提示', '请先选查询报表再进行预览');
				   	 }
                }
			},{
                xtype: 'button',
                text: '导入',
                icon: '/report/image/sysbutton/import.png',
                handler: function (self) {
            		 var AddfileForm=new Ext.FormPanel(
            		 {
            		  name : 'AddfileForm',
            		  frame : true,
            		  url : '/sys-report/ext-form/impQueryReport',
            		  fileUpload : true,
            		  width : 400,
            		  autoDestroy : true,
            		  items : [{
            		     xtype : 'filefield',
            		     emptyText : '选择上传报表文件',
            		     fieldLabel : '文件',
            		     name : 'upload',
            							labelWidth : 40,
//            		     buttonText : '',
            		     anchor : '95%',
            							margin:'15 0 0 15',
            							buttonText:'浏览',
            		      buttonConfig: {
            				                width: 70,
            				                icon: '/report/image/sysbutton/report.png'
            				             },
            		     validator: function(value){
            								var temp = value.split('.');
											var tmep1 = temp[temp.length-1];
				       var temp2 = tmep1.toLowerCase();
											var allowType = 'xml';
				       if (allowType.indexOf(temp2) == -1) {
				        return "不允许选择该类型文件，请选择xml文件！";
				       } else {
												return true;
											}
						           }
            		    }]
            		 });
            		 var AddfileWin=new Ext.Window(
            		 {
            	        title: '导入报表',
            	        width: 500,
            	        height: 150,
            	        layout: 'fit',
            	        plain: true,
            	        buttonAlign: 'center',
            	        items: AddfileForm,
            	        buttons: ['->',{
            	            text: '导入',
            	            handler: function (btn) {
            	            	if (AddfileForm.getForm().isValid()) {
            	            		Ext.MessageBox.show({
               	            		      title : '请稍等...',
               	            		      msg : '文件上传中...',
               	            		      progressText : '',
               	            		        width : 300,
               	            		      progress : true,
               	            		      closable : false,
               	            		      animEl : 'loding'
               	            		     });
									var formData = new FormData();
									formData.append('upload', AddfileForm.down('filefield').fileInputEl.dom.files[0]);
									// 发送请求时添加header头信息
									$.ajax({
										url: '/sys-report/ext-form/impQueryReport',
										type: 'POST',
										data: formData,
										resetForm: true,
										clearForm: true,
										processData: false,  //必须false才会避开jQuery对 formdata 的默认处理
										contentType: false,  //必须false才会自动加上正确的Content-Type
										success: function(response) {
											var json = JSON.parse(response);
											Ext.MessageBox.close();
											AddfileWin.close();
											var manageTreePanel = Ext.ComponentQuery.query('treepanel#manageTree')[0];
											manageTreePanel.getStore().load();
//	  	                                    Ext.ComponentQuery.query('button[name="import"]')[0].setHidden(true);
											Ext.ComponentQuery.query('button[name="save"]')[0].setDisabled(true);
											var mainPanel = Ext.ComponentQuery.query('panel#mainPanel')[0];
											mainPanel.removeAll(true);
											var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
											rightConfig.removeAll(true);
											conditions = {};
											fields = {};
											queryList = {};
											fieldsTemp = {};
											conditionsTemp = {};
											fieldsLength = 0;
											conditionlength = 0;
											initWindow_report_import(json.qidList);
										},
										failure: function(response) {
											var json = JSON.parse(response);
											var msg = json.message;
											Ext.MessageBox.show({
												title: '提示',
												msg: '导入失败:'+msg,
												width: 200,
												fn: function (btn) {
												}
											});
										}
									});
            	            	}
            	            }
            	        }, 
            	           {
            	            text: '关闭',
            	            handler: function () {
            	            	AddfileWin.close();
            	            }
            	        }]
            	    });
            	 AddfileWin.show();
                }
            },{
                xtype: 'button',
                text: '导出',
                icon: '/report/image/sysbutton/export.png',
                handler: function (self) {
                	initWindow_report_export();
                }
            },{
            	xtype:'button',
            	 text:'打印配置',
            	 icon: '/report/image/sysbutton/print.png',
            	 handler:function(){
            		 var manageTreePanel = Ext.ComponentQuery.query('treepanel#manageTree')[0];
				   	 var select = manageTreePanel.getSelectionModel().getSelection()[0];
				   	 if(select && select.get("leaf")){
				   		var id = select.get('id');
	                	var text = select.get('text');
                         $.post("/sys-report/getReportPrintConfig", {
                         	Q_ID: id
                         }, function (data) {
                            	var printConfig = data.print_config;
         	                	var headerLeft = "";
         	                	var headerCenter = "";
         	                	var headerRight = "";
         	                	var footerLeft = "";
         	                	var footerCenter = "";
         	                	var footerRight = "";
         	                	if(printConfig){
         	                		var tempPrint = printConfig.split('#');
         	                		if(tempPrint.length >= 2){
         	                			var printFooter = tempPrint[1];
         	                			var tempPrintFooter = printFooter.split('-');
         	                			footerLeft = tempPrintFooter[0];
         		                		if(tempPrintFooter.length >=2){
         		                			footerCenter = tempPrintFooter[1];
         		                		}
         		                		
         		                		if(tempPrintFooter.length >=3){
         		                			footerRight = tempPrintFooter[2];
         		                		}
         	                		}
         	                		var printHeader = tempPrint[0];
         	                		var tempPrintHeader = printHeader.split('-');
         	                		headerLeft = tempPrintHeader[0];
         	                		if(tempPrintHeader.length >=2){
         	                			headerCenter = tempPrintHeader[1];
         	                		}
         	                		
         	                		if(tempPrintHeader.length >=3){
         	                			headerRight = tempPrintHeader[2];
         	                		}
         							
         	                	}
         				   		var data = {
         				   				Q_ID: id,
         				   				HEADER_LEFT: headerLeft,
         				   				HEADER_CENTER: headerCenter,
         				   				HEADER_RIGHT: headerRight,
         				   				FOOTER_LEFT: footerLeft,
         				   				FOOTER_CENTER: footerCenter,
         				   				FOOTER_RIGHT: footerRight
                                      };
         				    	initWindow_report_print_config({
         				    		title:text,
         				    		data:data
         				    	});
                         }, "json");
				   	 }else{
				   		 Ext.MessageBox.alert('提示', '请先选查询报表再进行配置');
				   	 }
            	 }
            }];

function initLeftTree(){
	var panel = new Ext.panel.Panel({
        region:'west',
        xtype: 'panel',
        title: '报表',
        width: 250,
        layout: 'fit',
        items:[initTree()]
	});
	return panel;
}


function initTree(){
	var searchTbar=[//搜索区域
	          {
	              xtype: 'textfield',
	              width: '80%',
	              name: 'search_text',
	              emptyText: '请输入关键字检索',
	              enableKeyEvents: true,
	              listeners: {
	                  keypress: function (self, e) {
	                      if (e.getKey() == Ext.EventObject.ENTER) {
	                          treeSearch(self.up('treepanel'));
	                      }
	                  }
	              }
	          },
	          {
	              xtype: 'button',
	              text: '搜索',
	              handler: function (self) {
	                  treeSearch(self.up('treepanel'));
	              }
	          }
	      ]
    var tree=  new Ext.panel.Panel ({
    	layout: {
            type: 'vbox',
            align: 'stretch',
            flex: 1
        },
        height: '100%',
        border: true,
	    items:
	    [{
            width: '100%',
            flex: 5,
            xtype: 'treepanel',
            store: reportStroe,
            rootVisible: true,
            tbar:searchTbar,
            itemId: 'manageTree',
            listeners: {
            	afterlayout: function (self) {
					if(q_id==null){
						return ;
					}
            		var node = self.getStore().getNodeById(q_id);
					if(node==null){
						return ;
					}
					currentReport = node;
            		self.getSelectionModel().select(node);
//            		if(!mapIsEmpty(conditions) || !mapIsEmpty(fields) || !mapIsEmpty(queryList)){
//                		Ext.Msg.confirm('提示', q_title+'报表已修改是否保存修改的报表', function (btn_confirm) {
//			                if (btn_confirm == 'yes') {
//			                	saveReport();
////			                	changeReport(node);
//			                }else{
//			                	changeReport(node);
//			                }
//			            }); 
//                	}else{
//                		changeReport(node);
//                	}
    	    	},
                itemclick: function (view, record, item, index, e, eOpts) {
                	if(!record.get("leaf")){
                		return;
                	}
                	currentReport = record;
                	if(!deleteFlag && (!mapIsEmpty(conditionsTemp) || !mapIsEmpty(fieldsTemp) || !mapIsEmpty(queryList)
                			|| (conditionlength != 0 && conditionlength !=conditionList.length)
                			||(fieldsLength != getMapLength(fields)))){
                		Ext.Msg.confirm('提示', q_title+'报表已修改是否保存修改的报表', function (btn_confirm) {
			                if (btn_confirm == 'yes') {
			                	saveReport();
//			                	changeReport(record);
			                }else{
			                	changeReport(record);
			                }
			            }); 
                	}else{
                		changeReport(record);
                	}
                },
                'itemcontextmenu': function (view, record, item, index, e, eOpts) {
                	//禁用浏览器的右键相应事件
                    e.preventDefault();
                    e.stopEvent();
                }
            }
        },{
            width: '100%',
            flex: 5,
            xtype: 'treepanel',
            itemId: 'fieldTree',
            store: fieldStore,
            rootVisible: false,
            header:{
		    	xtype:'header',
		    	title:'字段',
		    	titleAlign:'left',
		    	height: 35,
		    	margin:'0 0 0 0',
	 	 		padding:'0 0 0 5',
	 	 		items:[{
	 	 			xtype: "label", 
	 	 			margin:'0 180 0 0',
	 	 			html:'<img src="/report/image/sysbutton/refresh_white.png" width="18px"; title="刷新" onclick ="refreshFieldTree()" />'
	 	 		}]
	 	 	},
  			enableDD: true,  
//            ddGroup:'fieldgroup',
            viewConfig: {
                plugins: {
                    ptype: 'treeviewdragdrop',
                    ddGroup: 'selDD',
                    enableDrop:false
                }
            },
            listeners: {
                itemclick: function (view, record, item, index, e, eOpts) {
                	if(timer){
                		timer = false;
                		task = new Ext.util.DelayedTask(function(){
                			var reportGrid=DSYGrid.getGrid('reportGrid');
		    				var reportStroe = reportGrid.getStore();
		    				var ddCol = reportGrid.getColumns()[ddTemp];
		    				if(reportGrid.getColumns()[ddTemp]){
		    					var dataIndex = ddCol.dataIndex;
	                			var id = record.get('id');
	                        	var fieldCode = record.get('code');//FIELD_TITLE  FIELD_CODE
	                        	if(codeMap[fieldCode]){
	                        		fields[dataIndex] = codeMap[fieldCode];
	                        	}else{
	                        		var fieldTitle = record.get('code');
	                            	var fieldType = record.get('field_type');
	                            	var data_type = record.get('data_type');
	                            	var data_url = record.get('data_url');
	                            	var data_url_field = record.get('data_url_field');
	                            	var url_type = record.get('url_type');
	                            	var is_show = record.get('is_show');
	                            	var is_url_param = record.get('is_url_param');
	                            	var is_sum = record.get('is_sum');
	                            	var is_newline = record.get('is_newline');
	                            	var sort_index = record.get('sort_index');
	                            	var field_length = record.get('field_length');
									var is_merge = record.get('is_merge');
	                            	var data_sort = record.get('data_sort');
	    		    			    if(fields[dataIndex]){
	    		    					fields[dataIndex].FIELD_CODE = fieldCode;
	    		    					fields[dataIndex].FIELD_TITLE= ddCol.text,
	    		    					fields[dataIndex].FIELD_TYPE=fieldType,
	    		    					fields[dataIndex].DATA_TYPE=data_type,
	    		    					fields[dataIndex].DATA_URL=data_url,
	    		    					fields[dataIndex].DATA_URL_FIELD=data_url_field,
	    		    					fields[dataIndex].URL_TYPE=url_type,
	    		    					fields[dataIndex].IS_SHOW=is_show,
	    		    					fields[dataIndex].IS_URL_PARAM=is_url_param,
	    		    					fields[dataIndex].IS_SUM=is_sum,
	    		    					fields[dataIndex].IS_NEWLINE=is_newline,
	    		    					fields[dataIndex].SORT_INDEX=sort_index,
	    		    					fields[dataIndex].FIELD_LENGTH=ddCol.width,
										fields[dataIndex].IS_MERGE=is_merge,
										fields[dataIndex].DATA_SORT=data_sort
	    		    				}else{
	    		    						fields[dataIndex]={
	    		    								F_ID:dataIndex,
	    		    								FIELD_CODE:fieldCode,
	    			    	                        FIELD_TITLE:ddCol.text,
	    			    	                        FIELD_TYPE:fieldType,
	    			    	                        DATA_TYPE:data_type,
	    			    	                        DATA_URL:data_url,
	    			    	                        DATA_URL_FIELD:data_url_field,
	    			    	                        URL_TYPE:url_type,
	    			    	                        IS_SHOW:is_show,
	    			    	                        IS_URL_PARAM:is_url_param,
	    			    	                        IS_SUM:is_sum,
	    			    	                        IS_NEWLINE:is_newline,
	    			    	                        SORT_INDEX:sort_index,
	    			    	                        FIELD_LENGTH:ddCol.width,
													IS_MERGE:is_merge,
	    			    	                        DATA_SORT:data_sort
	    		    						}
	    		    					}
			    				}
	                        	reportStroe.getAt(0).set(dataIndex,fieldCode);
//	                        	reportStroe.commitChanges();
	                        	$(reportGrid.getView().getCell(reportStroe.getAt(0),ddCol).dom).addClass("x-grid-cell-click");
	                        	oldTemp = ddCol;
			    				fieldsTemp[dataIndex] = fields[dataIndex];
					        	var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
					        	rightConfig.removeAll(true);
					        	rightConfig.setTitle("数据列配置");
					        	rightConfig.add(initFieldConfig({
				        			 f_id:dataIndex,
			                         data: fields[dataIndex],
			                         saveFlag:true
			                       }));
		    				}
                   		 	timer = true;
                    	});
                		task.delay(300);
                	}
                },
                itemdblclick: function(view, record, item, index, e, eOpts){
                	if(task){
                		task.cancel();
                		timer=true;
                	}
                },
                'itemcontextmenu': function (view, record, item, index, e, eOpts) {
                    //禁用浏览器的右键相应事件
                    e.preventDefault();
                    e.stopEvent();
                    currentNode = record;
                    fieldRightClick.showAt(e.getXY());
                },
                'itemmouseenter':function (view , record , item , index , e , eOpts) {
            		if(view.tip==undefined || view.tip == null){
            			view.tip=Ext.create('Ext.tip.ToolTip',{
                			target:view.el,//或者item
                			delegate:view.itemSelector,
                			trackMouse:true,
                			renderTo:Ext.getBody(),
                					itemLevel:1,
                					html:'右击添加条件'/*
                			listeners:{
                			beforeshow:functionupdateTipBody(tip){
                						  if(tip.itemLevel == 1){
                							  tip.update('鼠标左键：添加为条件、添加为列、交叉查询，鼠标右键：添加为条件、添加为列');
                						  }else{
                							  tip.update('鼠标左键：添加为列、交叉查询，鼠标右键：添加为列');
                						  }
                			}
                			}*/
                			});
            		}else{
            				view.tip.update('右击添加条件');
            		}
            	}
            }
	      }]
	});
    return tree;
}



/**
 * 初始化右侧panel，放置条件和grid
 */
function initPanel() {
    return Ext.create('Ext.panel.Panel', {
    	itemId:'mainPanel',
        height: '100%',
        flex: 5,
        region: 'center',
        collapsible: false,
        layout: {
            type: 'vbox',
            align: 'stretch'
        },
        border: false,
        items: [initSelect(),initGrid()],
    });
}


/**
 * 初始化右侧查询条件
 */
function initSelect() {
	var formPanel = new Ext.form.Panel({
	    width:'100%',
	    itemId:'condition',
	 	autoScroll: true, 
	 	layout:'column', 
	 	flex:4,
	    border: false,
	    frame: false,
	    title:q_title,
	    defaults:{
	    	labelAlign: "right",
	        xtype:"textfield",
	        labelWidth:110,
		    flex: 1,
		    columnWidth:0.3,
	        margin:0
	     },
	   items: [],
	   listeners: {
		   afterlayout:function ( self, layout, eOpts ) {
			   var browserInfo = getBrowserInfo();
   		       if(browserInfo["browser"]=="IE"){
	   		    	self.body.el.dom.onmousemove = function(){
	   		    		if(!FlagForPanel){
        		    		return;
        		    	}
	 				   if(!panelDragFlag){
	 					   return;
	 				   }
	 				   var record = panelDragTemp;
	 				   addCondition(record);
	 				   dragTemp = {};
	 				   panelDragTemp = {};
	 				   panelDragFlag=false;
	 			   }
   		       }else{
	   		    	self.body.el.dom.onmouseup = function(){
	   		    		if(!FlagForPanel){
        		    		return;
        		    	}
	 				   if(!panelDragFlag){
	 					   return;
	 				   }
	 				   var record = panelDragTemp;
	 				   addCondition(record);
	 				   dragTemp = {};
	 				   panelDragTemp = {};
	 				   panelDragFlag=false;
	 			   } 
   		       }
		       var panelEl=self.body.el.dom;
		       var panelDropTarget=Ext.create('Ext.dd.DropTarget',panelEl,{
		               ddGroup:'selDD',
		    		   notifyEnter:function(source,e,data){
		    			   panelDragTemp = data.records[0];  
		    		       panelDragFlag = true; 
		    		       FlagForPanel = true;
		    		       dragFlag = false;
		    		   },
		    		   notifyOut:function(source,e,data){
       		    		    dragTemp = {};
    	 				    panelDragTemp = {};
    	 				    panelDragFlag=false;
    	 				    dragFlag = false;
		    			},
		    	});
		   }
	   	}
    });
    return formPanel;
}



/**
 * 初始化右侧主表格
 */
function initGrid() {
	var config={
			width: '100%',
	        itemId: 'reportGrid',
	        flex:8,
	        checkBox:false,
	        columnLines: true,
	        forefit: true,
	        headerConfig: {
	            headerJson: columns,
	            columnAutoWidth: false
	        },
	        data:[],
	        isLocalStorage:false,
	        enableLocking:false,
	        sortableColumns:false,
	        //enableColumnMove:singleHeadFlag,
	        pageConfig: {
	            enablePage: false,
	            pageNum:false,
                pageSize:50
	        },
	        listeners: {
	        	afterLayout:function(self){
	        		    var gridPanel = DSYGrid.getGrid('reportGrid');
				    	var gridEl=gridPanel.body.el.dom;
				    	var gridDropTarget=Ext.create('Ext.dd.DropTarget',gridEl,{
				    			ddGroup:'selDD',
				    			notifyEnter:function(source,e,data){
				    				dragTemp = data.records[0];  
				    				dragFlag = true;
				    				FlagForPanel = false;
				    				panelDragFlag = false; 
				    			},
				    			notifyOut:function(source,e,data){
		        		    		dragTemp = {};
		     	 				    panelDragTemp = {};
		     	 				    panelDragFlag=false;
		    	 				    dragFlag = false;
				    			},
				    			notifyDrop:function(source,e,data){
				    				if(getMapLength(fields)==0){
				    					if(data.records){
				    						var addGuid = GUID.createGUID();
		 			            			var addColumn = {
		 			            					F_ID:addGuid,
		 			            					FIELD_TITLE:data.records[0].get('title'),
		 			            					FIELD_CODE:data.records[0].get('code'),
		 			            					FIELD_TYPE:data.records[0].get('field_type'),
		 			            					columns:new Array()
		 			            			};
		                        			configColumns.splice(0, 0,addColumn);
		                        			fieldConfAndShowFiled(addGuid);
				    					}
				    				}
				    			}
				    	});
				    	var panelHeaderEl=gridPanel.headerCt.el.dom;
			 			var panelHeaderDropTarget=Ext.create('Ext.dd.DropTarget',panelHeaderEl,{
			 			         ddGroup:'selDD',
			 			         notifyDrop:function(source,e,data){
			 			        	 var dataIndex = "";
			 			        	 var innerText = e.target.innerText;
			 			        	 var haveCount = 0;
			 			        	 var isLeaf = false;
			 			        	 if(data.records){
			 			        		 var repeatFlag = false;
			 			        		 var dragCode = source.dragData.records[0].get('code');
			 			        		 for(var key in fields){  
			                                 if(dragCode == fields[key].FIELD_CODE){
			                                	 repeatFlag = true;
			                                	 break;
			                                 }
			                             }
			 			        		 if(repeatFlag){
			 			        			 Ext.Msg.alert('提示', '此标题已存在不可添加！');
			 			        			 return;
			 			        		 }
			 			        	 }else{
			 			        		 if(!data.header.fullColumnIndex && data.header.fullColumnIndex != 0){
			 			        			 Ext.Msg.alert('提示', '非底级标题不可拖拽！');
			 			        			 return;
			 			        		 }
			 			        	 }
			 			        	 $.each(fields,function(key,value){
			 			              	 if(innerText == value.FIELD_TITLE){
			 			              		 dataIndex = key;
			 			              		 haveCount++;
			 			              	 }
			 			        	 });
			 			             if(haveCount > 1){
			 			            	 Ext.Msg.alert('提示', '重复的标题不可拖拽！');
			 			            	 return;
			 			             }
			 			             /*if(!dataIndex){
			 			            	for ( var i = 0; i < configColumns.length; i++) {
			 			            		var fieldTitle = configColumns[i].FIELD_TITLE;
			 			            		if(innerText == fieldTitle){
			                                	 dataIndex = configColumns[i].F_ID;
			                                	 break;
			                                 }
			 			            	}
			 			             }*/
			 			        	 if(data.records){
			 			        	     var addGuid = GUID.createGUID();
			 			        		 var addColumn = {
			 			   					F_ID:addGuid,
			 			   					FIELD_TITLE:data.records[0].get('title'),
			 			   					FIELD_CODE:data.records[0].get('code'),
			 			   					FIELD_TYPE:data.records[0].get('field_type'),
			 			   					columns:new Array()
			 			        		 };
				 			             if(dataIndex){
				 			            	for ( var i = 0; i < configColumns.length; i++) {
			 			            			if(configColumns[i].F_ID == dataIndex){
				 			            			configColumns.splice(i+1, 0,addColumn);
				 			            			break;
				 			            		}
			 			            			if(!singleHeadFlag){
			 			            				if(configColumns[i].columns && configColumns[i].columns.length > 0){
			 			            					addChildColumn(configColumns[i].columns,addColumn,dataIndex);
			 			            				}
					 			            	}
			 			            		}
				 			            	fieldConfAndShowFiled(addGuid);
				 			             }
			 			        	 }else{
			 			        		if(dataIndex){
			 			        			var moveColumn = {};
			 			        			var moveDataIndex = data.header.config.dataIndex;
			 			        			//configColumns.splice(fullColumnIndex, 1);
			 			        			for ( var i = 0; i < configColumns.length; i++) {
			 			        				if(configColumns[i].F_ID == moveDataIndex){
			 			        					moveColumn = configColumns[i];
			 			        					configColumns.splice(i, 1);
			 					            		break;
			 			        				}
			 			        				if(!singleHeadFlag){
			 			        					if(configColumns[i].columns && configColumns[i].columns.length > 0){
			 			        						moveColumn = removeChildColumn(configColumns[i].columns,moveDataIndex);
			 			        						if(!mapIsEmpty(moveColumn)){
			 			        							break;
			 			        						}
			 			        					}
			 						            }
			 				            	}
			 			        			for ( var i = 0; i < configColumns.length; i++) {
			 			        				if(configColumns[i].F_ID == dataIndex){
			 					            		configColumns.splice(i, 0,moveColumn);
			 					            		break;
			 			        				}
			 			        				if(!singleHeadFlag){
			 			        					if(configColumns[i].columns && configColumns[i].columns.length > 0){
			 			        						var addFlag = addChildColumn(configColumns[i].columns,moveColumn,dataIndex);
			 			        						if(addFlag){
			 			        							break;
			 			        						}
			 			        					}
			 						            }
			 				            	}
			 			        			fieldConf(configColumns,false,false);
		                        			var reportGrid = DSYGrid.getGrid('reportGrid');
		    	                        	var reportStroe = reportGrid.getStore();
		    	                        	reportStroe.removeAll();
		    	                        	reportStroe.insertData(0, showRecord);
		    	                        	reportGrid.reconfigure(reportStroe,columns);
		    	                    		Ext.resumeLayouts(true);
				 			             }
			 			        		//me.fireEvent('columnmove', me, header, fromIdx, toIdx);
			 			        	 }
			 			          }
			 			 });
			 			/*if(!singleHeadFlag){
			 				panelHeaderDropTarget.destroy();
			 			}*/
				    	var gridColumns = gridPanel.getColumns();
	                    for (var i = 0; i < gridColumns.length; i++) {
	                    	gridColumns[i].el.dom.ondblclick = null;
//	                    	gridColumns[i].el.dom.onmouseup = null;        
	                    	gridColumns[i].el.dom.dataIndex = gridColumns[i].dataIndex;
	                    	gridColumns[i].el.dom.setAttribute("dataIndex", gridColumns[i].dataIndex);
//	                    	gridColumns[i].el.dom.onmouseup = function(){
//	                    	};
	                    	gridColumns[i].el.dom.ondblclick = function () {
	                            var dataIndex = this.dataIndex;
	                            for ( var i = 0; i < configColumns.length; i++) {
	                        		if(configColumns[i].columns && configColumns[i].columns.length > 0){
	                        			columnChild(configColumns[i].columns,dataIndex);
	                        		}else{
	                        			if(configColumns[i].F_ID == dataIndex){
	                        				configColumns.splice(i, 1);
	                        				break;
	                        			}
	                        		}
	                        	}
	                            for(var key in fields){  
	                                if(key == dataIndex){
	                                	delete fields[key]; 
	                                }
	                            }
	                        	for(var key in fieldsTemp){
	                        		if(key == dataIndex){
	                        			delete fieldsTemp[key];
	                        		}
	                        	}
	                        	fieldConf(configColumns,true,false);
	                        	var reportGrid = DSYGrid.getGrid('reportGrid');
	                        	var reportStroe = reportGrid.getStore();
	                        	reportStroe.removeAll();
	                        	reportStroe.insertData(0, showRecord);
	                        	reportGrid.reconfigure(reportStroe,columns);
	                    		Ext.resumeLayouts(true); 
	                        };
	                    }
	        	},
	        	reconfigure: function (self) {
	        		var table = $($("#"+self.id )[0]);
	        		var reportGrid=DSYGrid.getGrid('reportGrid');
	        		table.find("tr").each(function(j){
	        			$(this).find("td").each(function(i){
		        			$(this).attr("cellIndex", i);
		        			var browserInfo = getBrowserInfo();
		        		    if(browserInfo["browser"]=="IE"){
		        		    	this.onmousemove = function(){
		        		    		if(FlagForPanel){
			        		    		return;
			        		    	}
		        		    		if(!dragFlag){
		        		    			return;
		        		    		}
		        		    		var cellIndex = $(this).attr("cellIndex");
		        		    		var reportGrid=DSYGrid.getGrid('reportGrid');
		        		    		var reportStroe = reportGrid.getStore();
		        		    		var ddCol = reportGrid.getColumns()[cellIndex];
		        		    		var record = dragTemp;
		        		    		if(reportGrid.getColumns()[cellIndex]){
		        		    			var dataIndex = ddCol.dataIndex;
		        		    			var id = record.get('id');
		        		    	    	var fieldCode = record.get('code');//FIELD_TITLE  FIELD_CODE
		        		    	    	if(codeMap[fieldCode]){
		        		    	    		fields[dataIndex] = codeMap[fieldCode];
		        		    	    	}else{
		        		    	    		var fieldTitle = record.get('code');
		        		    	        	var fieldType = record.get('field_type');
		        		    	        	var data_type = record.get('data_type');
		        		    	        	var data_url = record.get('data_url');
		        		    	        	var data_url_field = record.get('data_url_field');
		        		    	        	var url_type = record.get('url_type');
		        		    	        	var is_show = record.get('is_show');
		        		    	        	var is_url_param = record.get('is_url_param');
		        		    	        	var is_sum = record.get('is_sum');
		        		    	        	var is_newline = record.get('is_newline');
		        		    	        	var sort_index = record.get('sort_index');
		        		    	        	var field_length = record.get('field_length');
		        		    	        	var is_merge = record.get('is_merge');
		        		    	        	var data_sort = record.get('data_sort');
		        		    			    if(fields[dataIndex]){
		        		    					fields[dataIndex].FIELD_CODE = fieldCode;
		        		    					fields[dataIndex].FIELD_TITLE= ddCol.text,
		        		    					fields[dataIndex].FIELD_TYPE=fieldType,
		        		    					fields[dataIndex].DATA_TYPE=data_type,
		        		    					fields[dataIndex].DATA_URL=data_url,
		        		    					fields[dataIndex].DATA_URL_FIELD=data_url_field,
		        		    					fields[dataIndex].URL_TYPE=url_type,
		        		    					fields[dataIndex].IS_SHOW=is_show,
		        		    					fields[dataIndex].IS_URL_PARAM=is_url_param,
		        		    					fields[dataIndex].IS_SUM=is_sum,
		        		    					fields[dataIndex].IS_NEWLINE=is_newline,
		        		    					fields[dataIndex].SORT_INDEX=sort_index,
		        		    					fields[dataIndex].FIELD_LENGTH=ddCol.width,
		        		    					fields[dataIndex].IS_MERGE=is_merge,
		        		    					fields[dataIndex].DATA_SORT=data_sort
		        		    				}else{
		        		    						fields[dataIndex]={
		        		    								F_ID:dataIndex,
		        		    								FIELD_CODE:fieldCode,
		        		    		                        FIELD_TITLE:ddCol.text,
		        		    		                        FIELD_TYPE:fieldType,
		        		    		                        DATA_TYPE:data_type,
		        		    		                        DATA_URL:data_url,
		        		    		                        DATA_URL_FIELD:data_url_field,
		        		    		                        URL_TYPE:url_type,
		        		    		                        IS_SHOW:is_show,
		        		    		                        IS_URL_PARAM:is_url_param,
		        		    		                        IS_SUM:is_sum,
		        		    		                        IS_NEWLINE:is_newline,
		        		    		                        SORT_INDEX:sort_index,
		        		    		                        FIELD_LENGTH:ddCol.width,
															IS_MERGE:is_merge,
		        		    		                        DATA_SORT:data_sort
		        		    						}
		        		    					}
		        		    			}
		        		    	    	reportStroe.getAt(0).set(dataIndex,fieldCode);
//		        		    	    	reportStroe.commitChanges();
		        		    	    	if(oldTemp){
		        		    	    		if(reportGrid.getView().getCell(reportStroe.getAt(0),oldTemp)){
		        		    	    			$(reportGrid.getView().getCell(reportStroe.getAt(0),oldTemp).dom).removeClass("x-grid-cell-click");
		        		    	    		}
		        		    	    	}
		        		    	    	$(reportGrid.getView().getCell(reportStroe.getAt(0),ddCol).dom).addClass("x-grid-cell-click");
		        		    	    	oldTemp = ddCol;
		        		    			fieldsTemp[dataIndex] = fields[dataIndex];
		        		    	    	var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
		        		    	    	rightConfig.removeAll(true);
		        		    	    	rightConfig.setTitle("数据列配置");
		        		    	    	rightConfig.add(initFieldConfig({
		        		    				 f_id:dataIndex,
		        		    	             data: fields[dataIndex],
		        		    	             saveFlag:true
		        		    	           }));
		        		    		}
		        		    		dragFlag = false;
		        		    		dragTemp = {};
		     	 				    panelDragTemp = {};
		        		    	}
		        		    }else{
		        		    	this.onmouseup = function(){
		        		    		if(!dragFlag){
		        		    			return;
		        		    		}
		        		    		var cellIndex = $(this).attr("cellIndex");
		        		    		var reportGrid=DSYGrid.getGrid('reportGrid');
		        		    		var reportStroe = reportGrid.getStore();
		        		    		var ddCol = reportGrid.getColumns()[cellIndex];
		        		    		var record = dragTemp;
		        		    		if(reportGrid.getColumns()[cellIndex]){
		        		    			var dataIndex = ddCol.dataIndex;
		        		    			var id = record.get('id');
		        		    	    	var fieldCode = record.get('code');//FIELD_TITLE  FIELD_CODE
		        		    	    	if(codeMap[fieldCode]){
		        		    	    		fields[dataIndex] = codeMap[fieldCode];
		        		    	    	}else{
		        		    	    		var fieldTitle = record.get('code');
		        		    	        	var fieldType = record.get('field_type');
		        		    	        	var data_type = record.get('data_type');
		        		    	        	var data_url = record.get('data_url');
		        		    	        	var data_url_field = record.get('data_url_field');
		        		    	        	var url_type = record.get('url_type');
		        		    	        	var is_show = record.get('is_show');
		        		    	        	var is_url_param = record.get('is_url_param');
		        		    	        	var is_sum = record.get('is_sum');
		        		    	        	var is_newline = record.get('is_newline');
		        		    	        	var sort_index = record.get('sort_index');
		        		    	        	var field_length = record.get('field_length');
		        		    	        	var is_merge = record.get('is_merge');
		        		    	        	var data_sort = record.get('data_sort');
		        		    			    if(fields[dataIndex]){
		        		    					fields[dataIndex].FIELD_CODE = fieldCode;
		        		    					fields[dataIndex].FIELD_TITLE= ddCol.text,
		        		    					fields[dataIndex].FIELD_TYPE=fieldType,
		        		    					fields[dataIndex].DATA_TYPE=data_type,
		        		    					fields[dataIndex].DATA_URL=data_url,
		        		    					fields[dataIndex].DATA_URL_FIELD=data_url_field,
		        		    					fields[dataIndex].URL_TYPE=url_type,
		        		    					fields[dataIndex].IS_SHOW=is_show,
		        		    					fields[dataIndex].IS_URL_PARAM=is_url_param,
		        		    					fields[dataIndex].IS_SUM=is_sum,
		        		    					fields[dataIndex].IS_NEWLINE=is_newline,
		        		    					fields[dataIndex].SORT_INDEX=sort_index,
		        		    					fields[dataIndex].FIELD_LENGTH=ddCol.width,
												fields[dataIndex].IS_MERGE= is_merge,
												fields[dataIndex].DATA_SORT=data_sort
		        		    				}else{
		        		    						fields[dataIndex]={
		        		    								F_ID:dataIndex,
		        		    								FIELD_CODE:fieldCode,
		        		    		                        FIELD_TITLE:ddCol.text,
		        		    		                        FIELD_TYPE:fieldType,
		        		    		                        DATA_TYPE:data_type,
		        		    		                        DATA_URL:data_url,
		        		    		                        DATA_URL_FIELD:data_url_field,
		        		    		                        URL_TYPE:url_type,
		        		    		                        IS_SHOW:is_show,
		        		    		                        IS_URL_PARAM:is_url_param,
		        		    		                        IS_SUM:is_sum,
		        		    		                        IS_NEWLINE:is_newline,
		        		    		                        SORT_INDEX:sort_index,
		        		    		                        FIELD_LENGTH:ddCol.width,
															IS_MERGE:is_merge,
		        		    		                        DATA_SORT:data_sort
		        		    						}
		        		    					}
		        		    			}
		        		    	    	reportStroe.getAt(0).set(dataIndex,fieldCode);
//		        		    	    	reportStroe.commitChanges();
		        		    	    	if(oldTemp){
		        		    	    		if(reportGrid.getView().getCell(reportStroe.getAt(0),oldTemp)){
		        		    	    			$(reportGrid.getView().getCell(reportStroe.getAt(0),oldTemp).dom).removeClass("x-grid-cell-click");
		        		    	    		}
		        		    	    	}
		        		    	    	$(reportGrid.getView().getCell(reportStroe.getAt(0),ddCol).dom).addClass("x-grid-cell-click");
		        		    	    	oldTemp = ddCol;
		        		    			fieldsTemp[dataIndex] = fields[dataIndex];
		        		    	    	var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
		        		    	    	rightConfig.removeAll(true);
		        		    	    	rightConfig.setTitle("数据列配置");
		        		    	    	rightConfig.add(initFieldConfig({
		        		    				 f_id:dataIndex,
		        		    	             data: fields[dataIndex],
		        		    	             saveFlag:true
		        		    	           }));
		        		    		}
		        		    		dragFlag = false;
		        		    		dragTemp = {};
		     	 				    panelDragTemp = {};
		        		    	}
		        		    }
	        			});
	        		}); 
                },
	        	headerclick:function ( ct, column, e, t, eOpts ) {
	        		var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
	        		rightConfig.removeAll(true);
//            		mainPanel.add(initSelect());
	        		var f_id = column.dataIndex;
	        		var isLeaf=1;
	        		if(column.config.columns){
	        			isLeaf = 0;
	        		}
	        		/*if(!isLeaf){
	        			Ext.MessageBox.alert('提示', '请选择底级标题');
	        			return;
	        		}*/
//	        		var f_id = getConfigColumnsId(code);
	        		rightConfig.setTitle("数据列配置");
	        		if(fields[f_id]){
	        			rightConfig.add(initFieldConfig({
	        				f_id:f_id,
                            data: fields[f_id],
                            isLeaf: isLeaf
                        }));
	        		}else{
	        			$.post("/sys-report/getFieldInfo", {
	        				f_id:f_id
						}, function(jsondata) {
	                        var data = jsondata[0];
	                        if(mapIsEmpty(data)){
	                        	data={
	                        		F_ID:f_id,
	                        		FIELD_LENGTH:column.width,
	    	                        FIELD_TITLE:column.text		
	                        	};
	                        }
//	                        fields[f_id] = data;
//	                        fieldsTemp[f_id] = data;
	                        rightConfig.add(initFieldConfig({
	                        	f_id:f_id,
	                            data: data,
	                            isLeaf: isLeaf
	                        }));
	                    }, "json");
	        		}
	        	},
	        	cellclick: function ( self, td, cellIndex, record, tr, rowIndex, e, eOpts ){
	        		ddTemp = cellIndex;
	        		var trs = $(tr)[0].childNodes;
	        		for(var i=0;i<trs.length;i++){
	        			$(trs[i]).removeClass("x-grid-cell-click");
	        		}
	        		$(td).addClass("x-grid-cell-click");
	        		var reportGrid=DSYGrid.getGrid('reportGrid');
    				var reportStroe = reportGrid.getStore();
    				oldTemp = reportGrid.getColumns()[cellIndex];
    				var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
	    	    	rightConfig.removeAll(true);
	    	    	rightConfig.setTitle("数据列配置");
	    	    	rightConfig.add(initFieldConfig({
	    				 f_id:oldTemp.dataIndex,
	    	             data: fields[oldTemp.dataIndex],
	    	             saveFlag:true
	    	           }));
	        	},
	        	columnresize:function(ct,column,width,e){
	        		if(fields[column.dataIndex]){
	        			fields[column.dataIndex].FIELD_LENGTH = width;
		        		fieldsTemp[column.dataIndex] = fields[column.dataIndex];
		        		var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
		        		var rightPanel = rightConfig.down('form#window_zdpz_contentForm');
		        		if(rightPanel){
		        			var field_title = rightPanel.down('textfield[name="FIELD_TITLE"]').getValue();
		        			if(field_title == column.text){
		        				var fieldLength = rightPanel.down('numberfield[name="FIELD_LENGTH"]');
		        				fieldLength.setValue(width);
		        			}
		        		}
	        		}
	        	},
	        	headercontextmenu:function ( ct, column, e, t, eOpts ) {
	        		//禁用浏览器的右键相应事件
                    e.preventDefault();
                    e.stopEvent();
                    //if(singleHeadFlag){
                    	columnRightClick(column.config.dataIndex).showAt(e.getXY());
                    //}
	        	}
	        }
        };
	config.tbar = [{
        xtype: 'button',
        text: '导入表头',
        name: 'import',
        hidden:true,
        icon: '/report/image/file/xls.png',
        handler: function (self) {
    		 var AddfileForm=new Ext.FormPanel(
    		 {
    		  name : 'AddfileForm',
    		  frame : false,
    		  url : '/sys-report/ext-form/impQueryField',
    		  fileUpload : true,
    		  width : 400,
			  listeners: {
				  beforeaction: function(self, action, eOpts) {
					  action.headers = {
						  'test': 'header-value'
					  };
					  console.log(action);
				  }
		      },
    		  autoDestroy : true,
    				defaults: {
	                 margin: '5 10 5 10',
	                 labelAlign: "right",
	                 anchor : '95%',
	                 labelWidth: 94//控件默认标签宽度
    				},
    		  items : [{
				    			xtype: 'numberfield',
				    	        name: 'startrow',
				    	        fieldLabel: '表头开始行',
				    	        value: 1,
				    	        maxValue: 10,
				    	        minValue: 1,
				    	        allowBlank:false
    						},{
    							xtype: 'numberfield',
				    	        name: 'endrow',
				    	        fieldLabel: '表头结束行',
				    	        value: 1,
				    	        maxValue: 10,
				    	        minValue: 1,
				    	        allowBlank:false
    						},
    		                 {
    		     xtype : 'filefield',
    		     emptyText : '选择上传文件',
    		     fieldLabel : '文件',
    		     name : 'upload',
//    		     buttonText : '',
//    		     labelWidth: 88,
    							buttonText:'选择文件',
    		      buttonConfig: {
    				                width: 90,
    				                icon: '/report/image/sysbutton/report.png'
    				             },
    		     validator: function(value){
    								var temp = value.split('.');
									var tmep1 = temp[temp.length-1];
		       var temp2 = tmep1.toLowerCase();
									var allowType = 'xlsxlsx';
		       if (allowType.indexOf(temp2) == -1) {
		        return "不允许选择该类型文件，请选择Excel文件！";
		       } else {
										return true;
									}
				           }
    		    }]
    		 });
    		 var AddfileWin=new Ext.Window(
    		 {
    	        title: '导入表头',
    	        width: 500,
    	        height: 180,
    	        layout: 'fit',
    	        plain: true,
    	        border:false,
    	        buttonAlign: 'center',
    	        items: AddfileForm,
    	        buttons: ['->',{
    	            text: '导入',
    	            handler: function (btn) {
    	            	if (AddfileForm.getForm().isValid()) {
    	            		Ext.MessageBox.show({
       	            		      title : '请稍等...',
       	            		      msg : '文件上传中...',
       	            		      progressText : '',
       	            		        width : 300,
       	            		      progress : true,
       	            		      closable : false,
       	            		      animEl : 'loding'
							});
							var formData = new FormData();
							formData.append('file', AddfileForm.down('filefield').fileInputEl.dom.files[0]);
							var values = AddfileForm.getValues()
							formData.append('endrow', values["endrow"]);
							formData.append('startrow', values["startrow"]);
							// 发送请求时添加header头信息
							$.ajax({
								url: '/sys-report/ext-form/impQueryField',
								type: 'POST',
								data: formData,
								resetForm: true,
								clearForm: true,
								processData: false,  //必须false才会避开jQuery对 formdata 的默认处理
								contentType: false,  //必须false才会自动加上正确的Content-Type
								success: function(response) {
									var json = JSON.parse(response);
									Ext.MessageBox.close();
									AddfileWin.close();
									for(var i in fields){
										if(fields[i].FIELD_CODE){
											codeMap[fields[i].FIELD_CODE]=fields[i];
										}
									}
									var reportGrid=DSYGrid.getGrid('reportGrid');
									configColumns = json.list
									fieldConf(configColumns,true);
									var mainPanel = Ext.ComponentQuery.query('panel#mainPanel')[0];
									mainPanel.remove(reportGrid);
									mainPanel.add(initGrid());
									Ext.ComponentQuery.query('button[name="import"]')[0].setHidden(false);
									var reportGrid=DSYGrid.getGrid('reportGrid');
									var reportStroe = reportGrid.getStore();
									reportStroe.removeAll();
									reportStroe.insertData(0, showRecord);
									reportGrid.reconfigure(reportStroe,columns);
									Ext.resumeLayouts(true);
									var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
									rightConfig.removeAll(true);
									var id = currentReport.get('id');
									var q_is_title = currentReport.get('q_is_title');
									var text = currentReport.get('text');
									var table = currentReport.get('table');
									var unit = currentReport.get('unit');
									var q_is_right = currentReport.get('q_is_right');
									var q_is_page = currentReport.get('q_is_page');
									var q_is_sum = currentReport.get('q_is_sum');
									var q_is_openrun = currentReport.get('q_is_openrun');
									var q_is_button = currentReport.get('q_is_button');
									var q_remark = currentReport.get('q_remark');
									var q_note = currentReport.get('q_note');
									var right_level = currentReport.get('right_level');
									var export_level = currentReport.get('export_level');
									var export_data_format = currentReport.get('export_data_format');
									var data = {
										Q_ID: id,
										Q_IS_TITLE: q_is_title,
										Q_TITLE: text,
										Q_TABLE: table,
										MONEY_UNIT: unit,
										Q_IS_RIGHT: q_is_right,
										Q_IS_PAGE: q_is_page,
										Q_IS_SUM: q_is_sum,
										Q_IS_OPENRUN: q_is_openrun,
										Q_REMARK:q_remark,
										Q_NOTE:q_note,
										EXPORT_DATA_FORMAT:export_data_format,
										Q_IS_BUTTON: q_is_button,
										RIGHT_LEVEL:right_level,
										EXPORT_LEVEL:export_level
									};
									//queryList = data;
									rightConfig.setTitle("基本信息配置");
									rightConfig.add(initWindow_report_config_contentForm({
										edit:true,
										columnWidth:.99,
										data: data,
										saveFlag:true
									}));
								},
								failure: function(response) {
									var json = JSON.parse(response);
									var msg = json.message;
									Ext.MessageBox.show({
										title: '提示',
										msg: '导入失败:'+msg,
										width: 200,
										fn: function (btn) {
										}
									});
								}
							});
    	            	}
    	            }
    	        }, 
    	           {
    	            text: '关闭',
    	            handler: function () {
    	            	AddfileWin.close();
    	            }
    	        }]
    	    });
    	 AddfileWin.show();
        }
	}];
	var gridPanel = DSYGrid.createGrid(config);
    return gridPanel;
}

function initRightConfig(){
	var panel = new Ext.panel.Panel({
		region: 'east',     // center region is required, no width/height specified
        xtype: 'panel',
        layout: 'fit',
        width: 250,
        itemId: 'rightConfig',
        title:'',
        items:[]
	});
	return panel;
}


/**
 * 树检索
 * @param self 搜索按钮/检索框
 */
function treeSearch(tree,value) {
    //var tree = Ext.ComponentQuery.query('treepanel#manageTree')[0];
    var treeStroe = tree.getStore();
    var btn_search = tree.down('textfield[name="search_text"]');
    var roonodes = tree.getRootNode();//获取主节点
    var textValue = btn_search.getValue();
    if(value){
    	textValue = value;
    }
    if(textValue == null || textValue == 'undefined' || textValue.length == 0){
    	tree.getView().scrollTo(0, 0, true);
    	tree.getSelectionModel().clearSelections();
        return true;
    }
    //如果搜索框内容与上次搜索内容不一致，更新
    if (!btn_search.search_value || btn_search.search_value.toLowerCase() != textValue.toLowerCase()) {
    	tree.getSelectionModel().clearSelections();
        btn_search.search_start = 0;
        btn_search.search_value = textValue;
        if (typeof(btn_search.search_result)=="undefined") {
        	btn_search.search_result = new Array();
        	btn_search.search_resultCount = 0;
    	}
    }else{
    	if(typeof(tree.getSelectionModel().getSelection()[0])!="undefined"){
    		btn_search.search_result[btn_search.search_resultCount] = tree.getSelectionModel().getSelection()[0].data.text;
    		btn_search.search_resultCount = btn_search.search_resultCount+1;
        }
    }
    expandLeafByFinddata(roonodes,tree,textValue,btn_search.search_result,"treePanel",true,true);  //开始递归
    //循环store，检索搜索内容是否存在,
    var start_index = btn_search.search_start;
    var find = false;
    while (true) {
        btn_search.search_start++;
        if (btn_search.search_start >= treeStroe.getCount()) {
            btn_search.search_start = 0;
			btn_search.search_result = new Array();
			btn_search.search_resultCount = 0;
			expandLeafByFinddata(roonodes,tree,textValue,btn_search.search_result,"treePanel",true,true);  //开始递归
		}
        var record =treeStroe.getAt(btn_search.search_start);
        var value = record.get('text') + record.get('id');
        if (value.toLowerCase().indexOf(textValue.toLowerCase()) >= 0) {
        	tree.expandPath(record.getPath('id'));
            var scorll_height = btn_search.search_start * (tree.getView().getNodes()[0].clientHeight) > 100 ? btn_search.search_start * (tree.getView().getNodes()[0].clientHeight) - 100 : 0;
            tree.getSelectionModel().select(record);
            tree.getView().scrollTo(0, scorll_height, true);
            find = true;
            break;
        }
        if (start_index == btn_search.search_start) {
            break;
        }
    }
    if (!find) {
        Ext.toast({
            html: '无此数据',
            closable: false,
            align: 't',
            slideInDuration: 400,
            minWidth: 400
        });
    }
}

//var renderHander = function(cmp) { 
//	 new Ext.dd.DropTarget(cmp.body.dom, {  
//         ddGroup: 'fieldgroup',  
//         notifyDrop: function(ddSource, e, data) {  
////             if (!data.node.hasChildNodes()) {  
////                 cmp.setTitle(data.node.parentNode.attributes.text);  
////                                 }  
//             return false;  
//         }  
//     });  
//} 
